/**
 * DSM - Distributed Search Manager
 * Developed by Milspec Research International Pty Ltd
 * $Author: skahl $
 * $Revision: 1.5 $
 * $Date: 2007/12/04 04:41:22 $
 * (c)Copyright 2004
 * education.au limited
 * DEST
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the names education.au limited, DEST nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 * To the extent permitted by law, the copyright owners of this software and
 * its contributors:
 * (i) exclude all warranties in relation to the software; and
 * (ii) exclude liability for all losses, costs, expenses and damages arising
 * in any way from the use of the software whether arising from or in
 * relation to breach of contract, negligence or any other tort, in equity
 * or otherwise. If the software is in breach of a warranty which is
 * implied by law, the copyright owners and contributors liability is
 * limited to the replacement of the software.
 *
 * @author	gsingh
 */

package au.edu.educationau.opensource.dsm.adapters.contenthandler;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import au.edu.educationau.opensource.dsm.adapters.SearchAdapterProperties;
import au.edu.educationau.opensource.dsm.obj.ResultCategory;
import au.edu.educationau.opensource.dsm.obj.ResultMetadata;
import au.edu.educationau.opensource.dsm.obj.SearchCriteria;
import au.edu.educationau.opensource.dsm.obj.SearchResult;
import au.edu.educationau.opensource.dsm.util.StringUtils;
import au.edu.educationau.opensource.dsm.worker.ResultSetUnifier;

public class OpenSearchContentHandler extends DefaultHandler {
	private SearchResult result = new SearchResult();
	private ResultCategory cat = new ResultCategory();
	private ArrayList results = new ArrayList();
	private ArrayList categories = new ArrayList(5);
	private ArrayList metadata = new ArrayList(5);

	private StringBuffer titleBuffer = new StringBuffer();
	private StringBuffer descriptionBuffer = new StringBuffer();
	private StringBuffer identifierBuffer = new StringBuffer();
	private StringBuffer relevanceBuffer = new StringBuffer();
	private StringBuffer categoryNameBuffer = new StringBuffer();
	private StringBuffer filetypeBuffer = new StringBuffer();

	private int count = 0;
	private int found = 0;
	private int nextRecordPosition = 0;

	private String currentElement = "";
	private String previousElement = "";
	private SearchAdapterProperties props = new SearchAdapterProperties();
	private SearchCriteria criteria = new SearchCriteria();
	private String resultSetID = "";

	private String diagnosticCode = "";
	private boolean withinItem = false;

	boolean done = false;

	/***/
	public int getFound() {
		return found;
	}

	/***/
	public int getNextRecordPosition() {
		return nextRecordPosition;
	}

	/***/
	public String getResultSetID() {
		return resultSetID;
	}

	/***/
	public int getCount() {
		return (int) results.size();
	}

	/***/
	public ArrayList getResults() {
		return results;
	}

	/***/
	public String getDiagnosticCode() {
		return diagnosticCode;
	}

	/**
	 * @param props
	 */
	public void setSearchAdapterProperties(SearchAdapterProperties props) {
		this.props = props;
	}

	public SearchAdapterProperties getSearchAdapterProperties() {
		return props;
	}

	/**
	 * @param criteria
	 */
	public void setSearchCriteria(SearchCriteria criteria) {
		this.criteria = criteria;
	}

	/**
	 * @param ch
	 * @param ch_start
	 * @param ch_length
	 * @exception SAXException
	 */
	public void characters(char[] ch, int ch_start, int ch_length) throws SAXException {
		String val = String.copyValueOf(ch, ch_start, ch_length);
		// SUMMARY
		if (withinItem) {
			if (currentElement.equals("title")) {
				titleBuffer.append(val);
			}

			if (currentElement.equals("link")) {
				identifierBuffer.append(val);
			}

			// RSS uses description, Atom uses summary
			if (currentElement.equals("description") || currentElement.equals("summary")) {
				descriptionBuffer.append(val);
			}

			if (currentElement.equals("dsm:relevance")) {
				relevanceBuffer.append(val);
			}

			if (currentElement.equals("dsm:filetype")) {
				filetypeBuffer.append(val);
			}
		}

		if (currentElement.equals("opensearch:totalResults")) {
			if (!StringUtils.isEmpty(val)) {
				found = Integer.valueOf(val).intValue();
			}
		}
	}

	/**
	 * @param ch
	 * @param ch_start
	 * @param ch_length
	 * @exception SAXException
	 */
	public void ignorableWhitespace(char[] ch, int ch_start, int ch_length) throws SAXException {
	}

	/**
	 * @param uri
	 * @param localName
	 * @param qName
	 * @exception SAXException
	 */
	public void endElement(java.lang.String uri, java.lang.String localName, java.lang.String qName) throws SAXException {
		currentElement = "";

		// support RSS & Atom
		if (qName.equals("item") || qName.equals("entry")) {
			result.setDescription(descriptionBuffer.toString().trim());
			result.setLink(identifierBuffer.toString().trim());
			result.setTitle(titleBuffer.toString().trim());
			result.setSource(props.getAdapterCode());
			result.setCollectionName(props.getDisplayTitle());
			if (!filetypeBuffer.toString().equals("")) {
				metadata.add(new ResultMetadata("mimetype", filetypeBuffer.toString()));
			}
			try {
				result.setRelevance(Float.parseFloat(relevanceBuffer.toString()) / 100F);
			} catch (Throwable t) {
			}
			metadata.trimToSize();
			ResultMetadata[] metadataArray = new ResultMetadata[metadata.size()];
			result.setResultMetadata((ResultMetadata[]) metadata.toArray(metadataArray));
			float combinedHitFrequency = ResultSetUnifier.getHitFrequency(criteria.getQueryArray(), result.getTitle(), result.getDescription(), criteria.getKeywordConstraint(), criteria.isCaseSensitive());
			result.setHitFrequency(combinedHitFrequency);
			results.add(result);
			withinItem = false;
		}

	}

	/**
	 * @param target
	 * @param data
	 * @exception SAXException
	 */
	public void processingInstruction(String target, String data) throws SAXException {
	}

	/**
	 * @param uri
	 * @param localName
	 * @param qName
	 * @param attr
	 * @exception SAXException
	 */
	public void startElement(java.lang.String uri, java.lang.String localName, java.lang.String qName, Attributes attr) throws SAXException {
		this.currentElement = qName;

		// support RSS & Atom
		if (qName.equals("item") || qName.equals("entry")) {
			result = new SearchResult();
			titleBuffer = new StringBuffer();
			descriptionBuffer = new StringBuffer();
			identifierBuffer = new StringBuffer();
			relevanceBuffer = new StringBuffer();
			filetypeBuffer = new StringBuffer();
			metadata = new ArrayList(5);
			withinItem = true;
		} else if (qName.equals("link")) {
			// Atom uses an attribute to store the link
			if (identifierBuffer.length() == 0) {
				String type = attr.getValue("type");
				if ("text/html".equals(type)) {
					identifierBuffer.append(attr.getValue("href"));
				}
			}
		}
	}

}
